<?php

namespace App\Services;

use App\Models\BookRule;
use App\Models\Child;
use Illuminate\Http\Request;

/**
 * Class ChildService
 * @package App\Services
 */
class ChildService
{
    /**
     * @param Request $request
     * @param Child $child
     * @return Child
     * 小程序 - 新增/编辑 子女卡时，给符合条件的子女自动订餐
     */
    public function autoOrder(Request $request, Child $child)
    {
        $queryBookRule = [];
        $user = \Auth::user();
        $query = BookRule::query()->where([
            ['school_id', $user->school_id],
            ['eat_date', '>=', now()->addDay(1)->format('Y-m-d')],
            ['is_cancel', BookRule::NOT_CANCELED],
            ['is_settled', BookRule::NOT_SETTLED]
        ]);
        // 早餐变为自动
        if(intval($request->morning_rule) === 1) {
            array_push($queryBookRule, BookRule::EAT_TYPE_BREAKFAST);
        }
        // 午餐变为自动
        if(intval($request->lunch_rule) === 1) {
            array_push($queryBookRule, BookRule::EAT_TYPE_LUNCH);
        }
        // 晚餐变为自动
        if(intval($request->dinner_rule) === 1) {
            array_push($queryBookRule, BookRule::EAT_TYPE_DINNER);
        }
        $bookRules = $query->whereIn('eat_type', $queryBookRule)->get();
        if ($bookRules->count() > 0) {
            foreach ($bookRules as $bookRule) {
                if ($bookRule->isActive && !$user->isBookedByRule($bookRule, $child->id)) {
                    BookOrderService::generateChildrenOrder($user, $bookRule, $child->id);
                }
            }
        }
        return $child;
    }
}
